<template>
  <div v-if="type !== null" class="mainBox">
      <el-row style="height: 100%;">
          <el-col style="height: 100%;overflow: hidden;" :span="14" v-if="imageData.invoiceTypeName !== '手工录入' && imageData.invoiceUrl">
              <div class="mainBox_title">
                  <div>发票影像
                      <span v-if="imageData.invoiceTypeName">-</span>
                      <a>{{ imageData.invoiceTypeName }}</a>
                  </div>
              </div>
              <div class="mainBox_img">
                <img v-if="imageData.vatInvoiceVerify === 'SUCCESS'" src="./images/real-success.png" class="__ui_real">
                <img v-if="imageData.vatInvoiceVerify === 'DEFEAT'" src="./images/real-fail.png" class="__ui_real">
                <ImgSwiper :imgList="preImgList" :form="form"></ImgSwiper>  
                <!-- <el-image
                      :src="imageData.invoiceUrl"
                      :preview-src-list="srcList"
                      :initial-index="1"
                      fit="cover"
                      lazy
                      >
                  </el-image> -->
              </div>
          </el-col>
          <el-col class="detailTextBox" :span="imageData.invoiceTypeName !== '手工录入' && imageData.invoiceUrl ? 10 : 24">
              <div class="mainBox_title">
                <div>发票信息<span v-if="imageData.invoiceTypeName">-</span><a>{{ imageData.invoiceTypeName }}</a></div>
                <div class="mainBox_title_btn" v-if="isDisable === false">
                    <el-button type="primary" size="small" @click="submit">确定</el-button>
                    <!-- <el-button size="small" @click="handleClose">取消</el-button> -->
                </div>
              </div>
              <div class="mainBox_Form">
                <el-form>
                  <el-form-item v-if="ishandwork" label="发票类型" label-width="110px" class="type-form">
                    <el-select  v-model="type" filterable clearable @change="typeChange" style="width:100%" placeholder="请选择发票类型">
                      <el-option
                          v-for="item in typeOptions"
                          :key="item.type"
                          :label="item.label"
                          :value="item.type"
                          :disabled="isDisable"
                      />
                    </el-select>
                    </el-form-item>
                  </el-form>
                  <billCildForm ref="billCildFormRef" :key="billCildFormRefKey" :allListForm="form" :FormData="FormData" :BaseData="BaseData" :Datalist="Datalist" :ruleList="ruleList" :isDisable="isDisable" :invoiceType="type" :detailListNew="detailListNew" :detailListBase="detailListBase" :baseRatio="baseRatio" @on-submit="saveData"/>
              </div>
          </el-col>
      </el-row>
  </div>
  <div v-else class="nullBox">
      <div>
          <img :src="textNullImg"/>
          <div class="text">暂无内容</div>
      </div>
  </div>
</template>

<script setup>
import textNullImg from './images/textNull.png'
import billCildForm from './components/billCildForm.vue'
import { ElMessage } from "element-plus";
import { typeList31, newRules31, newRules33, typeList11, newRules11, typeList2, newRules2,
typeList5, newRules5, typeList0, newRules0, newRules35, typeList1, newRules1, typeList121,
newRules121, typeList122, newRules122, typeList8, newRules8, typeList9, newRules9,
typeList20, newRules20, typeList40, newRules40, newRules41,
typeList41, typeList13, newRules13, typeList10, newRules10,
} from './components/config'
import { typeOptions } from './components/typeList'
import { numMulti, numAdd, numSub } from '@/util'
import api from '@/api'
import { computed, watchEffect } from 'vue';
import ImgSwiper from './components/imgSwiper.vue'
defineOptions({
  name: 'ScanBillForm',
  autoImport: true
})
const props = defineProps({
  imageData: {
      type: Object,
      default: () => {}
  },
  isDisable: {
      type: Boolean,
      default: false
  }
})

const formRef = ref(null)
const billCildFormRef = ref(null)
const billCildFormRefKey = ref('')
const form = ref({...props.imageData})
const oldForm = ref({})
const srcList = ref([])
const type = ref(null)
const FormData = ref({})
const BaseData = ref({})
const Datalist = ref([])
const ruleList = ref({})
const detailListBase = ref([]) // 明细原始值
const detailListNew = ref([]) // 明细最新的值
const ishandwork = ref(false)
const emit = defineEmits(['on-submit'])
const removeDuplicateObj = (arr) => {
  let obj = {};
  arr = arr.reduce((newArr, next) => {
    obj[next.url] ? "" : (obj[next.url] = true && newArr.push(next));
    return newArr;
  }, []);
  return arr;
};
const preImgList = computed(() => {
  let result = []
  console.log(form.value, '~!aaaa', form.value.rect)
  if (form.value.invoiceUrl) {
    result.push({
      url: form.value.invoiceUrl,
      rect: form.value.showRect ? { ...form.value.rect || {}, angle: form.value.angle }: null 
    })
  }
  if (form.value.invoiceDetailDTOS) {
    form.value.invoiceDetailDTOS.forEach(item => {
      if (item.imgUrl) {
        const tar = item.imgUrl.split(',')
        tar.forEach(childItem => {
          result.push({
            url: childItem,
            rect: null
          })
        })
        
      }
    })
  }
  result = removeDuplicateObj(result)
  console.log(result, 'resultresult')
  return result
})
const submit = ()=>{
  billCildFormRef.value.saveFormData()
}
const transferDetails = (array) => {
  const keyMap = {
    "货物或应税劳务、服务名称" : "goodsName",
    "金额" : "excludingTaxAmount",
    "税额": "taxAmount",
    "税率": "taxRate"
  }
  for(var i = 0;i < array.length;i++){
    var obj = array[i];
    for(var key in obj){
      var newKey = keyMap[key];
      if(newKey){
        obj[newKey] = obj[key];
        delete obj[key];
      }
    }
  }
  return array
}
const generateDetail = (arr) => {
  let tar = JSON.parse(JSON.stringify(arr))
  tar.forEach(item => {
    if (item.taxAmount === '***') {
      item.taxAmount = 0
    }
  })
  return tar
}
const transferText = (arr, dataType, allVal) => {
  let result = {}
  let detailList = []
  console.log(arr, 'arr55555')
  if (typeOptions[type.value].details && allVal.invoiceDetailDTOS) {
    if (dataType === 'new') {
      detailListNew.value = generateDetail([...allVal.invoiceDetailDTOS])
    }
  }
  if (typeOptions[type.value].details && allVal.invoiceDetailBase) {
    if (dataType === 'base') {
      const tar = JSON.parse(allVal.invoiceDetailBase)
      const inner = Array.isArray(tar) ? tar: [tar]
      detailListBase.value = generateDetail([...inner])
    }
  }
  arr.forEach(item => {
    if (!typeOptions[type.value].details) {
      item.row = -1
    }
    if (item.row * 1 === -1) {
      result[item.name] = item.value
    } else {
      if (!detailList[item.row]) {
        detailList[item.row] = {}
      }
      detailList[item.row][item.name] = item.value
    }
    if (type.value == 41 || type.value == 40) {
      // 增值税电子发票单独处理
      if (item.name === '合计税额') {
        result['合计税额'] = item.value
      }
      if (item.name === '合计金额') {
        result['合计金额'] = item.value
      }
    }
  })
  if (!allVal.invoiceDetailDTOS) {
    if (dataType === 'new') {
      detailListNew.value = transferDetails([...detailList])
    }
  }
  if (!allVal.invoiceDetailBase) {
    if (dataType === 'base') {
      detailListBase.value = transferDetails([...detailList])
    }
  }
  console.log(result, 'resultresult', detailList)
  return result
}
const initData = (newVal) => {
  Datalist.value = []
  oldForm.value = {...newVal}
  type.value = newVal.invoiceType
  srcList.value = []
  srcList.value.push(newVal.invoiceUrl)
  form.value = newVal
  ishandwork.value = form.value.inputBy === 0 ? true : false
  FormData.value = {}
  if(form.value && form.value.otherText) FormData.value = transferText(JSON.parse(form.value.otherText), 'new', form.value)
  if(form.value && form.value.otherBaseText) BaseData.value = transferText(JSON.parse(form.value.otherBaseText), 'base', form.value)
  console.log(FormData.value, 'FormData.valueFormData.value')
  initDataValue();
  if(ishandwork.value && !form.value.ocrInput){
      let status = true
      Datalist.value.forEach((item,index)=>{
          if(item.prop === '附件'){
              status = false
          }
      })
      if(status){
          const newObj = {
              label: '上传附件',
              prop: '附件',
              value: '附件',
              el: 'uploadForm',
              labelWidth: '120px',
              placeholder: '请输入附件',
              fileList: []
          }
          Datalist.value.push(newObj)
      }
  }
}
const baseRatio = ref(0)
const setBaseTaxRatio = (id) => {
// if (!ishandwork.value) {
//   return false
// }
id = id ? id * 1 : null
if (id == 2 || id == 5 || id == 9 || id == 10) {
  api.ticket.querytax_byid({
    pageNum: 1,
    pageSize: 1,
    invoiceType: id
  }).then(res => {
    if (res.list && res.list.length > 0) {
      const baseAmount = numAdd(FormData.value['票价'] || 0, FormData.value['燃油附加费'] || 0)
      const taxRatio = numMulti(res.list[0].invoiceTax, 0.01)
      const taxAmount = numMulti(baseAmount / (numAdd(taxRatio, 1)), taxRatio)
      baseRatio.value = taxRatio
      let amountExcludeTax = id != 5 ? FormData.value['票价'] ? numSub(FormData.value['票价'], taxAmount): '' : FormData.value['合计金额'] ? numSub(FormData.value['合计金额'], taxAmount): ''
      FormData.value = {
        ...FormData.value,
          ...{ '税率':  res.list[0].invoiceTax + '%',
          '税额': taxAmount,
          '不含税票价': amountExcludeTax
        }
      }
    }
  })
}

}
const initDataValue = ()=>{
  type.value = type.value * 1
  if(type.value === 31){
      // 增值税专用发票
      Datalist.value = [...typeList31]
      ruleList.value = newRules31
  }
  if(type.value === 32){
      // 增值税电子专用发票
      Datalist.value = [...typeList31]
      ruleList.value = newRules31
  }
  if(type.value === 33){
      // 增值税普通发票
      Datalist.value = [...typeList31]
      ruleList.value = newRules33
  } 
  if(type.value === 34){
      // 增值税电子普通发票
      Datalist.value = [...typeList31]
      ruleList.value = newRules31
  }
  if(type.value === 40){
      // 电子发票(普通发票)
      Datalist.value = [...typeList40]
      ruleList.value = newRules40
  }
  if(type.value === 41){
      // 电子发票(增值税专用发票)
      Datalist.value = [...typeList41]
      ruleList.value = newRules41
  }
  if(type.value === 11){
      // 增值税普通发票（卷式）
      Datalist.value = [...typeList11]
      ruleList.value = newRules11
  }
  if(type.value === 2){
      // 铁路行业发票
      Datalist.value = [...typeList2]
      ruleList.value = newRules2
      // if(FormData.value['出发时间']){
      //     FormData.value['开票日期'] = FormData.value['出发时间'].split('日')[0]
      // }else{
      //     FormData.value['开票日期'] = ''
      // }
  }
  if(type.value === 5){
      // 航空运输电子客票行程单
      Datalist.value = [...typeList5]
      ruleList.value = newRules5
  }
  if(type.value === 0){
      // 出租车发票
      Datalist.value = [...typeList0]
      ruleList.value = newRules0
      // if(FormData.value['日期']){
          // FormData.value['开票日期'] = FormData.value['日期']
      // }else{
          // FormData.value['开票日期'] = ''
      // }
  }
  if(type.value === 35){
      // 增值税电子普通发票（通行费）
      Datalist.value = [...typeList31]
      ruleList.value = newRules35
  }
  if(type.value === 1){
      // 定额发票
      Datalist.value = [...typeList1]
      ruleList.value = newRules1
  }
  if(type.value === 121){
      // 机动车销售统一发票
      Datalist.value = [...typeList121]
      ruleList.value = newRules121
  }
  if(type.value === 122){
      // 二手车销售统一发票
      Datalist.value = [...typeList122]
      ruleList.value = newRules122
  }
  if(type.value === 8){
      // 通用机打发票
      Datalist.value = [...typeList8]
      ruleList.value = newRules8
  }
  if(type.value === 9){
      // 汽车票
      Datalist.value = [...typeList9]
      ruleList.value = newRules9
  }
  if(type.value === 10){
      // 轮船票
      Datalist.value = [...typeList10]
      ruleList.value = newRules10
  }
  if(type.value === 13){
      // 过路过桥费发票
      Datalist.value = [...typeList13]
      ruleList.value = newRules13
  }
  if(type.value === 20){
      // 业务单据
      Datalist.value = [...typeList20]
      ruleList.value = newRules20
  }
  setBaseTaxRatio(type.value)
}

// 修改发票类型
const typeChange = ()=>{
  billCildFormRefKey.value = new Date()
  form.value.invoiceType = type.value
  form.value.invoiceTypeName = typeOptions[type.value].label
  initDataValue()
  if(ishandwork.value && !form.value.ocrInput){
      let status = true
      Datalist.value.forEach((item,index)=>{
          if(item.prop === '附件'){
              status = false
          }
      })
      if(status){
          const newObj = {
              label: '上传附件',
              prop: '附件',
              value: '附件',
              el: 'uploadForm',
              labelWidth: '120px',
              placeholder: '请输入附件',
              fileList: []
          }
          Datalist.value.push(newObj)
      }
  }
}
const getPostData = (otherText) => {
let result = []
for(let key in otherText) {
  result.push({
    row: -1,
    name: key,
    value: otherText[key]
  })
}
// detailListNew.value.forEach((item, index) => {
//   for(let key in item) {
//     result.push({
//       row: index,
//       name: key,
//       value: item[key]
//     })
//   }
// })
return JSON.stringify(result)
}
const saveData = (data) => {
  if(typeOptions[type.value].Validity(data, detailListNew.value)){
      form.value.invoiceAmount = typeOptions[type.value].getinvoiceAmount(data)
      form.value.invoiceNo = typeOptions[type.value].getinvoiceNo(data)
      form.value.invoiceCode = typeOptions[type.value].getinvoiceCode(data)
      form.value.invoiceDate = typeOptions[type.value].getinvoiceDate(data) ? typeOptions[type.value].getinvoiceDate(data).replace(/年|月/g, '-').replace(/日/g, ' ') : ''
      if (type.value == 121) {
        form.value.invoiceTaxAmount = data['增值税税额']
        form.value.invoiceTax = data['增值税税率或征收率']
      } else {
        if ((form.value.invoiceTax === undefined || form.value.invoiceTax === null) && data['税率'] !== undefined) {
          form.value.invoiceTax = data['税率'].replace(/%/g, '')
        }
        form.value.invoiceTaxAmount = data['合计税额'] || data['税额']
      }
      if (type.value === 0) {
        form.value.licensePlateNumber = data['车牌号'] || ''
      }
      form.value.invoiceDetailDTOS = detailListNew
      form.value.otherText = getPostData(data)
      if (data['附件'] && data['附件'].length > 0) {
        form.value.invoiceUrl = data['附件'][0].fileUrl
      }
      emit('on-submit', {...form.value})
  }else{
      
  }
}

const handleClose = () =>{
  form.value = oldForm.value
  if(form.value && form.value.otherText){
      FormData.value = JSON.parse(form.value.otherText)
  } else{
      FormData.value = {}
  }
}

// watchEffect(() => {
//   if(props.imageData) {
//     initData(props.imageData)
//     billCildFormRefKey.value = new Date()
//   }
// })

watch(() => props.imageData,(newVal) => {
  if(newVal){
    console.log(newVal, 'newVal')
    initData(newVal)
    billCildFormRefKey.value = new Date()
  }
})

defineExpose({
initData,
submit,
handleClose
})
</script>

<style lang="scss" scoped>
.mainBox {
border-radius: 8px;
background: #ffffff;
padding: 24px;
height: 100%;
overflow: hidden;
.mainBox_title {
  font-size: 16px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #262626;
  display: flex;
  justify-content: space-between;
  a {
    font-size: 16px;
    font-weight: 500;
  }
}
.mainBox_img {
  position: relative;
  margin-top: 18px;
  width: calc(100% - 30px);
  margin-right: 30px;
  height: calc(100% - 40px);
  display: flex;
  align-items: center;
  justify-content: center;
  background: #F8FAFC;
  padding: 0 10px;
  .__ui_real{
    width: 224px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    z-index:3;
  }
  img {
    width: 100%;
    padding-right: 30px;
  }
}
.mainBox_Form {
  margin-top: 24px;
  padding: 0 8px
}
}
.nullBox{
  background:#ffffff;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  img{
      width: 200px;
  }
  .text{
      text-align: center;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #8C8C8C;
  }
}
.detailTextBox{
  height: 100%;
  overflow: auto;
  :deep(.el-input.is-disabled .el-input__inner){
    color: #333
  }
}
.detailTextBox::-webkit-scrollbar-thumb{
  background-color: #D9D9D9;
}

</style>
<style lang="scss">
.type-form {
  width: 100%;
  .el-form-item__label {
    text-align: left;
  }
}
</style>
